package com.hgyc.mom.common.converter;

import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class PptxImageConverter implements ImageConverter {

    private static final Logger logger = LoggerFactory.getLogger(PptxImageConverter.class);

    @Override
    public List<byte[]> convertToImages(byte[] inputFile) {
        logger.info("PptxImageConverter.convertToImages.PDF转图片开始");
        // 存储所有图片字节数组的列表
        List<byte[]> imagesList = new ArrayList<>();

        try (InputStream pptInputStream = new ByteArrayInputStream(inputFile)) {
            // 创建PPT文档对象
            XMLSlideShow ppt = new XMLSlideShow(pptInputStream);

            // 获取PPT中的所有幻灯片
            List<XSLFSlide> slides = ppt.getSlides();


            // 遍历每一张幻灯片并转换为图片
            for (XSLFSlide slide : slides) {
                BufferedImage image = renderSlideAsImage(slide); // 获取缩略图
                // 将图片转换为byte[]
                byte[] imageBytes = convertImageToBytes(image);

                imagesList.add(imageBytes);
            }

            logger.info("PptxImageConverter.convertToImages.PDF转图片结束");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("PptxImageConverter.convertToImages.PDF转图片错误", e);
        }
        return imagesList;
    }

    private static BufferedImage renderSlideAsImage(XSLFSlide slide) throws IOException {
        BufferedImage image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB); // 调整图像大小
        slide.draw(image.createGraphics());
        return image;
    }

    private static byte[] convertImageToBytes(BufferedImage image) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }
}
